package net.anzhuo.controller.db;

import java.text.SimpleDateFormat;
import java.util.ArrayList;

import java.util.Date;
import java.util.List;

import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;

import lombok.extern.slf4j.Slf4j;
import net.anzhuo.common.utils.CompanyNameUtils;
import net.anzhuo.common.utils.DateUtil;

import net.anzhuo.entity.GsBase;
import net.anzhuo.entity.GsBranch;

import net.anzhuo.entity.GsGudong;

import net.anzhuo.entity.GsOuttouzi;
import net.anzhuo.entity.GsQuery;
import net.anzhuo.entity.GsRelationship;
import net.anzhuo.entity.db.spiderman.DetailList;
import net.anzhuo.entity.db.spiderman.Gudong;
import net.anzhuo.entity.db.spiderman.JsonRootBean;
import net.anzhuo.entity.db.spiderman.Kg;
import net.anzhuo.entity.db.spiderman.Kzr;
import net.anzhuo.entity.db.spiderman.SyrNames;
import net.anzhuo.entity.db.spiderman.Oper;
import net.anzhuo.entity.db.spiderman.Syr;
import net.anzhuo.entity.db.spiderman.Touzi;
import net.anzhuo.entity.db.syncdata.PairValue;
import net.anzhuo.entity.db.syncdata.QueryKeyNoResult;
import net.anzhuo.entity.db.syncdata.UpdateKeyNoResult;
import net.anzhuo.entity.equitypenetration.EnquityPenetrationResult;
import net.anzhuo.entity.equitypenetration.EnquityResult;
import net.anzhuo.entity.equitypenetration.KeyNoListResult;
import net.anzhuo.entity.relationship.CompanyRelationshipPojo;
import net.anzhuo.service.GsBaseService;
import net.anzhuo.service.GsBranchService;

import net.anzhuo.service.GsGudongService;
import net.anzhuo.service.GsOuttouziService;
import net.anzhuo.service.GsQueryService;
import net.anzhuo.service.GsRelationshipService;

@RestController
@Slf4j
public class RelationshipController {

	
	
	@Autowired
	private TransportClient client;
	
	
	@Autowired
	private GsRelationshipService gsRelationshipService;
	
	@Autowired
	private GsBaseService gsBaseService;
	
	@Autowired
	private GsBranchService gsBranchService;
	
	@Autowired
	private GsGudongService gsGudongService;
	
	
	@Autowired
	private GsQueryService gsQueryService;
	
	
	@Autowired
	private GsOuttouziService gsOutouziService;
	
	public List<DetailList> getDetailListRep(List<DetailList> list,Gudong gudong)
	{
	
		for(int i=0;i<list.size();i++)
		{
			DetailList g=list.get(i);
			if(g.DetailCount>0)
			{
				g.DetailList=this.getDetailListRep(g.DetailList,gudong);
			}
			
			if(g.KeyNo.substring(0,1).equals("p"))
			{
				List<GsBase> gsBaselist=gsBaseService.getByNameList(gudong.Name);
				GsBase gsBase=new GsBase(); 
				for(int x=0;x<gsBaselist.size();x++)
				{
					if(x==0)
					{
						gsBase=gsBaselist.get(x);
					}else
					{
						gsBaseService.delete(gsBaselist.get(x).getId());
					}
				}
				if(gsBase!=null)
				{
				List<GsGudong> listGudong=gsGudongService.getByMd5(gsBase.getMd5());
				for(GsGudong g1:listGudong)
				{
					if(g1.getShareholder()!=null)
					{
						if(g1.getShareholder().trim().equals(g.Name))
						{
							g1.setMd5(g.KeyNo);
							if(g1.getCapitaltype().equals("自然人股东"))
							{
								g1.setCapitaltype("1");
							}else if(g1.getCapitaltype().equals("企业法人"))
							{
								g1.setCapitaltype("2");
							}else if(g1.getCapitaltype().equals("法人股东"))
							{
								g1.setCapitaltype("3");
							}else if(g1.getCapitaltype().equals("事业法人"))
							{
								g1.setCapitaltype("4");
							}
							gsGudongService.update(g1);							
						}
					}
				}
				}
			}else
			{
				List<GsBase> gsBaselist=gsBaseService.getByNameList(gudong.Name);
				GsBase gsBase=new GsBase(); 
				for(int x=0;x<gsBaselist.size();x++)
				{
					if(x==0)
					{
						gsBase=gsBaselist.get(x);
					}else
					{
						gsBaseService.delete(gsBaselist.get(x).getId());
					}
				}
				if(gsBase!=null)
				{
					List<GsBranch> listBranch=gsBranchService.getByMd5(gudong.Name);
					for(GsBranch g2:listBranch)
					{
						if(g2.getEnterpriseName()!=null)
						{
						if(g.Name.equals(g2.getEnterpriseName().trim()))
						{ 
							g.KeyNo=g2.getMd5();
						}
						}
					}
				}
			}
			list.set(i, g);
		}
		return list;
	}
	
	
	public List<DetailList> getDetailListTouZiRep(List<DetailList> list,Touzi touzi)
	{
	
		
		for(int i=0;i<list.size();i++)
		{
			DetailList g=list.get(i);
			if(g.DetailCount>0)
			{
				g.DetailList=this.getDetailListTouZiRep(g.DetailList,touzi);
			}
			List<GsBase> gsBaselist=gsBaseService.getByNameList(touzi.Name);
			GsBase gsBase=new GsBase(); 
			for(int x=0;x<gsBaselist.size();x++)
			{
				if(x==0)
				{
					gsBase=gsBaselist.get(x);
				}else
				{
					gsBaseService.delete(gsBaselist.get(x).getId());
				}
			}

		 if(gsBase!=null)
		 {
		 GsOuttouzi go=new GsOuttouzi();
		 go.setCoMd5(gsBase.getMd5());
		 go.setEnterpriseName(g.Name);
		 List<GsOuttouzi> listOut=gsOutouziService.getListByName(go);
		  for(GsOuttouzi g1:listOut)
		  {
			 g.KeyNo=g1.getMd5();
		  }
		 }
			
		list.set(i, g);
		}
		return list;
	}
	
  
   
   public List<SyrNames> getSYRNames(List<SyrNames> list,Syr syr)
   {
	   ArrayList<SyrNames> lista=new ArrayList<SyrNames>();
	   for(SyrNames g:list)
	   {
	
			   GsGudong gss=new GsGudong();
			   gss.setShareholder(g.Name);
			   gss.setCoMd5(syr.KeyNo);
			   List<GsGudong> listOper= gsGudongService.getByName(gss);
			   if(listOper.size()>0)
			   {
				   GsGudong gsGudong=  listOper.get(0);
			       gsGudong.setMd5(g.KeyNo);	   			
			   }		   
		   lista.add(g);
	   }
	   
	   return lista;
   }
	
	@RequestMapping("/RelationshipKeyNoList")
	public QueryKeyNoResult RelationshipKeyNoList(String status) {
		log.info("===>RelationshipKeyNoList="+status);
		long startTime=System.currentTimeMillis();
		QueryKeyNoResult qknr=new QueryKeyNoResult();		
		try {
	
			qknr.setStatus("200");
			qknr.setMessage("查询成功");
			GsRelationship gp=new GsRelationship();
			gp.setStatus(status);
		   List<GsRelationship> list=gsRelationshipService.getList(gp);
		  
		   List<PairValue> keyNoList=new ArrayList<PairValue>();
		   PairValue pv=new PairValue();
		   for(GsRelationship g:list)
		   {
			  
			   pv=new PairValue();
			   pv.setKeyNo(g.getKeyNo());
			   if(gsBaseService.getByMd5(g.getKeyNo())!=null)
					   {
				   if(gsBaseService.getByMd5(g.getKeyNo()).getName()!=null&&!gsBaseService.getByMd5(g.getKeyNo()).getName().equals(""))
			       {
					   pv.setName(gsBaseService.getByMd5(g.getKeyNo()).getName());
					   pv.setCreditCode(gsBaseService.getByMd5(g.getKeyNo()).getCreditCode());
					   log.info("Name not null="+g.getKeyNo()+":"+pv.getName());
			       }else
					   {
			    	   if(gsBaseService.getByMd5(g.getKeyNo()).getCreditCode()!=null&&!gsBaseService.getByMd5(g.getKeyNo()).getCreditCode().equals(""))
			    	   {
			    		  // pv.setName(gsBaseService.getByMd5(g.getKeyNo()).getCreditCode());
			    		  // log.info("Name is null and credit is not null="+pv.getName());
			    	   }else
			    	   {
			    		   continue;
			    	   }
			    	   }
					   }	   
			   keyNoList.add(pv); 
		   }
		   qknr.setCount(keyNoList.size());
		   log.info("size="+keyNoList.size());
		   qknr.setKeyNoList(keyNoList);
		}catch(Exception e1)
		{
			log.info(e1.getMessage());
		}	
		 long endTime=System.currentTimeMillis();
		 float excTime=(float)(endTime-startTime)/1000;
		 log.info(" EnquityKeyNoList 执行时间："+excTime+"s");
		return qknr;
	}
	@RequestMapping("/UpdateRelationshipKeyNo")
	public UpdateKeyNoResult UpdateRelationshipKeyNo(String keyNo,String data,String status) {
		log.info("===>UpdateRelationshipKeyNo="+keyNo);
		long startTime=System.currentTimeMillis();
		UpdateKeyNoResult qknr=new UpdateKeyNoResult();
		
		try {
	
			qknr.setStatus("200");
			qknr.setMessage("查询成功");
			GsRelationship gp=new GsRelationship();
			gp.setKeyNo(keyNo);
			gp.setStatus(status);
			gp.setData(data);
			Date date= new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String str = sdf.format(date);
			
			gp.setUpdateTime(str);
			gsRelationshipService.update(gp);
		 
		}catch(Exception e1)
		{
			log.info(e1.getMessage());
		}
		
		
		 long endTime=System.currentTimeMillis();
		 float excTime=(float)(endTime-startTime)/1000;
		 log.info(" UpdateEnquityKeyNo 执行时间："+excTime+"s");
		return qknr;
	}
	@RequestMapping("/CompanyRelationshipLocal")
	public EnquityPenetrationResult RelationshipPenetration(String keyword) {
		log.info("===>CompanyRelationship="+keyword);
		EnquityPenetrationResult ep=new EnquityPenetrationResult();
		QueryBuilder query = QueryBuilders.boolQuery()
				.must(QueryBuilders.boolQuery()
					.must(QueryBuilders.matchPhraseQuery("md5",keyword)));
		ArrayList<KeyNoListResult> list=new ArrayList<KeyNoListResult>();
		KeyNoListResult knr=new KeyNoListResult();
		SearchResponse response = client.prepareSearch("gs").setTypes("gs_base").setQuery(query).addSort("weight", SortOrder.DESC).addSort("_score", SortOrder.DESC).setFrom((Integer.parseInt("1")-1)*200).setSize(200).execute().actionGet();
		if (response.getHits().getTotalHits()>0) {
			{
				for (SearchHit searchHit : response.getHits()) {	
					knr=new KeyNoListResult();
					knr.setKeyNo((String)searchHit.getSource().get("md5"));
					knr.setName((String)searchHit.getSource().get("name"));
					list.add(knr);
					log.info("name="+(String)searchHit.getSource().get("name"));
					GsRelationship gs=new GsRelationship();
					gs.setKeyNo(knr.getKeyNo());
					gs.setLegal(knr.getLegal());
					gs.setName(knr.getName());
					gs.setStatus("0");
					gs.setUpdateTime(DateUtil.getDate("yyyy-MM-dd"));
					List<GsRelationship> li=gsRelationshipService.getBycoMd5(knr.getKeyNo());
					if(li.size()==0)
					{
						gsRelationshipService.save(gs);
					}else
					{
						gs.setId(li.get(0).getId());
						long a=DateUtil.getDateTimeLong(DateUtil.getDate("yyyy-MM-dd HH:mm:ss"))-DateUtil.getDateTimeLong(gs.getUpdateTime());
					    int del=(int)a/(24*60*60*1000);
					    if(del>1)
					    {
					    	gsRelationshipService.update(gs);
					    }
						if(li.get(0).getData().length()>200)
						{
						gs.setStatus("1");
						gsRelationshipService.update(gs);
						}else
						{
							gsRelationshipService.update(gs);
						}
					}
				}
			}
		}
		
		List<GsRelationship> listResult=gsRelationshipService.getBycoMd5(keyword);
		GsRelationship gp=new GsRelationship();
		if(listResult.size()>0)
		{
		
			gp=listResult.get(0);
			while(gp.getStatus().equals("0"))
			{
				listResult=gsRelationshipService.getBycoMd5(keyword);
				if(listResult.size()>0)
				{
					gp=listResult.get(0);
					
				}
			}
		}
		String data=gp.getData();

		ep.setData(data);
		long startTime=System.currentTimeMillis();
		long endTime=System.currentTimeMillis();
		float excTime=(float)(endTime-startTime)/1000;
		log.info(" CompanyRelationship 执行时间："+excTime+"s");
		return ep;
	}
	
	@RequestMapping("/CompanyRelationship")
	public EnquityPenetrationResult RelationshipPenetrationLocal(String keyword) {
		log.info("===>CompanyRelationshipLocal="+keyword);
		EnquityPenetrationResult ep=new EnquityPenetrationResult();
		QueryBuilder query = QueryBuilders.boolQuery()
				.must(QueryBuilders.boolQuery()
					.must(QueryBuilders.matchPhraseQuery("md5",keyword)));
		ArrayList<KeyNoListResult> list=new ArrayList<KeyNoListResult>();
		if(keyword==null||keyword.equals("")||keyword.equals("null")||keyword.equals("500"))
		{
			return ep;
		}
		KeyNoListResult knr=new KeyNoListResult();
		SearchResponse response = client.prepareSearch("gs").setTypes("gs_base").setQuery(query).addSort("weight", SortOrder.DESC).addSort("_score", SortOrder.DESC).setFrom((Integer.parseInt("1")-1)*200).setSize(200).execute().actionGet();
		if (response.getHits().getTotalHits()>0) {
			{
				for (SearchHit searchHit : response.getHits()) {	
					knr=new KeyNoListResult();
					knr.setKeyNo((String)searchHit.getSource().get("md5"));
					knr.setName((String)searchHit.getSource().get("name"));
					list.add(knr);
					log.info("name="+(String)searchHit.getSource().get("name"));
					GsRelationship gs=new GsRelationship();
					gs.setKeyNo(knr.getKeyNo());
					gs.setLegal(knr.getLegal());
					GsBase gsBase=new GsBase();
					gsBase=gsBaseService.getByCreditCode(keyword);
					if(gsBase!=null)
					{
						knr.setName(gsBase.getName());
					}
					gs.setName(knr.getName());
					gs.setStatus("0");
					gs.setUpdateTime(DateUtil.getDate("yyyy-MM-dd"));
					List<GsRelationship> li=gsRelationshipService.getBycoMd5(knr.getKeyNo());
					if(li.size()==0)
					{
						gsRelationshipService.save(gs);
					}else
					{
						gs.setId(li.get(0).getId());
						if(li.get(0).getData().length()>200)
						{
						gs.setStatus("1");
						gsRelationshipService.update(gs);
						}else
						{
					    gsRelationshipService.update(gs);
						}
					}
				}
			}
		}
		
		List<GsRelationship> listResult=gsRelationshipService.getBycoMd5(keyword);
		GsRelationship gp=new GsRelationship();
		if(listResult.size()>0)
		{
		
			gp=listResult.get(0);
			while(gp.getStatus().equals("0"))
			{
				listResult=gsRelationshipService.getBycoMd5(keyword);
				if(listResult.size()>0)
				{
					gp=listResult.get(0);
					
				}
			}
		}
		//keyNo replace
		String data=gp.getData();
		data=data.replace("\n", "");
		data=data.replace("\\N", "");
		CompanyRelationshipPojo crp=JSON.parseObject(data, CompanyRelationshipPojo.class);
		//GraphProperties
		net.anzhuo.entity.relationship.Success success=crp.getSuccess();
		List<net.anzhuo.entity.relationship.Results> lisNodetResult=success.getResults();
		for(int i=0;i<lisNodetResult.size();i++)
		{
			net.anzhuo.entity.relationship.Results g=lisNodetResult.get(i);
			List<net.anzhuo.entity.relationship.Data> datalist=g.data;
			for(int j=0;j<datalist.size();j++)
			{
				net.anzhuo.entity.relationship.Data g1=datalist.get(j);
				net.anzhuo.entity.relationship.Graph graph=g1.graph;
				List<net.anzhuo.entity.relationship.Nodes> nodes=graph.nodes;
				for(int z=0;z<nodes.size();z++)
				{
					net.anzhuo.entity.relationship.Nodes node=graph.nodes.get(z);
					if(node.labels.size()==1)
					{
						String flag=node.labels.get(0);
						if(flag.equals("Company"))
						{
							List<GsBase> listGsBase=gsBaseService.getByNameList(CompanyNameUtils.getEnglishBraces(node.properties.name));
							List<GsBase> listGsBaseSec=gsBaseService.getByNameList(CompanyNameUtils.getChineseBraces(node.properties.name));
							if(listGsBase.size()==0&&listGsBaseSec.size()==0)
							{
								GsQuery gsQuery=new GsQuery();
								gsQuery.setName(node.properties.name);
								gsQuery.setKeyNo(node.properties.keyNo);
								List<GsQuery> listQuery=gsQueryService.getBycoMd5(gsQuery);
								if(listQuery.size()==0)
								{
									gsQuery.setStatus("0");
									gsQueryService.save(gsQuery);
								}else
								{
									gsQuery.setStatus("0");
									gsQuery.setId(listQuery.get(0).getId());
									gsQueryService.update(gsQuery);
								}
							}else
							{
								GsBase gsBase=new GsBase();
								if(listGsBase.size()>0)
								{
									gsBase=listGsBase.get(0);
								}else 
								{
									gsBase=listGsBaseSec.get(0);
								}
								node.properties.keyNo=gsBase.getMd5();
							}
						}
					}
					
					nodes.set(z, node);
				}
				graph.setNodes(nodes);
				g1.setGraph(graph);
				g.data.set(j, g1);
			}
			lisNodetResult.set(i, g);
		}      
		success.setResults(lisNodetResult);
		crp.setSuccess(success);
        String dataLocal=JSON.toJSONString(crp);
		ep.setData(dataLocal);
		long startTime=System.currentTimeMillis();
		long endTime=System.currentTimeMillis();
		float excTime=(float)(endTime-startTime)/1000;
		log.info(" RelationshipPenetrationLocal 执行时间："+excTime+"s");
		return ep;
	}
	
	//result
	@RequestMapping("/RelationshipSearchResult")
	public EnquityResult RelationshipPenetrationSearchResult(String keyword) {
		log.info("===>RelationshipSearchResult="+keyword);
		EnquityResult ep=new EnquityResult();
		SearchResponse response=null;
		if (keyword.length()>4)
		{
		QueryBuilder query = QueryBuilders.boolQuery()
				.must(QueryBuilders.boolQuery()
					.must(QueryBuilders.matchPhraseQuery("name",keyword)));
		
		 response = client.prepareSearch("gs").setTypes("gs_base").setQuery(query).addSort("weight", SortOrder.DESC).addSort("_score", SortOrder.DESC).setFrom((Integer.parseInt("1")-1)*200).setSize(200).execute().actionGet();
		}else
		{
			QueryBuilder query = QueryBuilders.boolQuery()
					.must(QueryBuilders.boolQuery()
						.must(QueryBuilders.matchPhraseQuery("legal",keyword)));
			 response = client.prepareSearch("gs").setTypes("gs_base").setQuery(query).addSort("weight", SortOrder.DESC).addSort("_score", SortOrder.DESC).setFrom((Integer.parseInt("1")-1)*200).setSize(200).execute().actionGet();
		
		}
		List<net.anzhuo.entity.equitypenetration.Result> list=new ArrayList<net.anzhuo.entity.equitypenetration.Result>();
		if (response.getHits().getTotalHits()>0) {
			{
				for (SearchHit searchHit : response.getHits()) {	
					net.anzhuo.entity.equitypenetration.Result r=new net.anzhuo.entity.equitypenetration.Result();
					r.setKeyNo((String)searchHit.getSource().get("md5"));
					r.setName((String)searchHit.getSource().get("name"));
				    r.setLegal((String)searchHit.getSource().get("legal"));
					r.setProvince(((String)searchHit.getSource().get("province")));
					GsRelationship gs=new GsRelationship();
					gs.setKeyNo(r.getKeyNo());
					gs.setLegal(r.getLegal());
					gs.setName(r.getName());
					gs.setStatus("0");
					gs.setUpdateTime(DateUtil.getDate("yyyy-MM-dd"));
					List<GsRelationship> li=gsRelationshipService.getBycoMd5(r.getKeyNo());
					if(li.size()==0)
					{
					gsRelationshipService.save(gs);
					}else
					{
						gsRelationshipService.update(gs);
					}
					list.add(r);
				}
			}
		}
		ep.setResult(list);
		long startTime=System.currentTimeMillis();
		 long endTime=System.currentTimeMillis();
		 float excTime=(float)(endTime-startTime)/1000;
		 log.info(" RelationshipSearchResult 执行时间："+excTime+"s");
		return ep;
	}
}
